package pers.gxm.javaweb;

import java.io.*;

public class MyHttpResponse {

    private final static String BASE_PATH = "/src/main/resources";

    private OutputStream os;

    public MyHttpResponse(OutputStream os){
        this.os = os;
    }

    public void  sendDirect(String uri){
        String url = System.getProperty("user.dir") + BASE_PATH + uri;
        System.out.println("url = " + url);

        File file = new File(url);
        byte[] result;
        String response;
        if(file.exists()){
            FileInputStream fis;
            try {
                 fis = new FileInputStream(file);
              byte[] bytes = new byte[fis.available()];
              fis.read(bytes);
                String msg = new String(bytes);
                response = response("200", msg);
                System.out.println(response);

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            String msg = new String(bytes);

        }else{
            String msg = "404 File Not Found!";
             response = response("404", msg);
        }
        result = response.getBytes();
        try {
            os.write(result);
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private String response(String code ,String msg){
        return "HTTP/1.1" + code + "\r\n"
                + "Content-Type: text/html\r\n"
                + "Content-Length: " + msg.length()
                + "\r\n\r\n"
                + msg;
    }
}
